<template>
  <div>
    <!-- Modify dialog start -->
    <el-dialog
        v-model="modifyVisible"
        title="修改数据集"
        width="30%"
        align-center
    >
      <div>
        <el-form :model="modifyData" status-icon ref="modifyRef" label-width="80px" class="demo-ruleForm">
          <el-form-item label="名称" prop="imgName">
            <el-input v-model="modifyData.imgName"></el-input>
          </el-form-item>

          <el-form-item style="margin: 20px auto auto;">
            <el-button type="primary" @click="modifySubmitForms">提交</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
    <!-- Modify dialog end -->

    <!-- datasets_content start -->
    <div class="content_box" v-for="item in setsData" :key="item.id" style="color:black">
      <div class="imgsets_name" style="padding-left: 24px; padding-top: 30px;">{{ item.labelsetName }}</div>
      <div class="imgsets_describe">{{ item.represent }}</div>
      <div class="imgsets_describe">{{ item.createTime }}</div>
    </div>
    <!-- datasets_content end -->

    <!-- list_data start -->
    <div class="list_data_box">
      <div class="line">
      </div>
      <div class="gui_box">
        <el-input
            v-model="input3"
            placeholder="Please input"
            class="input-with-select"
        >
          <template #append>
            <el-button :icon="Search" />
          </template>
        </el-input>
        <input type="file" @change="uploadFiles" webkitdirectory style="margin-left:20px">
        <el-button type="danger" :icon="Delete" @click="removeView"/>
        <el-button type="primary" :icon="Refresh" @click="getList"/>
      </div>

      <el-table :data="displayedData" v-model:selected-keys="selectedKeys" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="labelId" label="标签Id"></el-table-column>
        <el-table-column prop="labelName" label="标签名称"></el-table-column>
        <el-table-column prop="labelsetId" label="标签集Id"></el-table-column>
        <el-table-column prop="imgId" label="对应影像id"></el-table-column>
        <el-table-column prop="createTime" label="创建时间"></el-table-column>
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button type="primary" @click="toThreeD(row)" style="margin-top: 10px;margin-left: 0px;border: none;background-color: transparent;color:black">查看</el-button>
            <el-button type="success" :icon="Download" @click="download(row)" style="margin-top: 10px;margin-left: 0px;border: none;background-color: transparent;color:black"></el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="demo-pagination-block" style="margin-left: 30px;margin-top: 15px;">
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 30, 40]"
            :small="small"
            :disabled="disabled"
            :background="background"
            layout="total, sizes, prev, pager, next, jumper"
            :total="listData.length"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <!-- list_data end -->

  </div>
</template>

<script>
import {onMounted, reactive, ref} from "vue";
import labels from "@/api/labels";
import {ElDialog, ElForm, ElLoading, ElMessage, ElMessageBox} from "element-plus";
import {useRoute} from "vue-router/dist/vue-router";
import datasets from "@/api/datasets";
import { Delete, Search, Download, Refresh } from '@element-plus/icons-vue';
import router from "@/router";

export default {
  name: "labels",
  components:{
    ElDialog,
    ElLoading,
    ElForm
  },

  setup(){
    let userId = ""
    let labelsetId = ""

    // 渲染数据模型
    let listData = reactive([])
    const selectedKeys = reactive([])
    let displayedData = reactive([])
    let setsData = reactive([])

    // 选择数据模型
    const imgIds = []

    // form修改数据模型
    const modifyData = ref({
      imgName:'',
    })
    const modifyRef = ref(null)
    let modifyImgId = 0
    const modifyVisible = ref(false)

    // 分页控制
    const currentPage = ref(1);
    const pageSize = ref(10);

    onMounted(() =>{
      const route = useRoute()
      console.log(route.params.labelsetId)
      labelsetId = route.params.labelsetId
      userId = JSON.parse(localStorage.getItem('userData')).userId.toString()

      getList()
    })

    // 查
    function getList(){
      let da = {}
      da.labelsetId = labelsetId

      console.log(da)
      labels.list(da).then(res => {
        console.log(res)
        if(res.code == 200) {
          listData.length = 0
          listData.splice(0, res.data.labels.length, ...res.data.labels)
          currentPage.value = 1
          pageSize.value = 10
          const start = (currentPage.value - 1) * pageSize.value
          const end = start + pageSize.value
          displayedData.length = 0
          displayedData.splice(start, end, ...listData.slice(start, end))

          displayedData.forEach(function(element){
            console.log(element.createTime.replace('T','\n'))
            element.createTime = element.createTime.replace('T',' ')
          })

          setsData.length = 0
          setsData.push(res.data.labelsets)
        }else{
          console.log(res)
        }
      })
    }

    // 改
    const modifyView = (row) => {
      console.log(row)
      modifyVisible.value = true
      modifyData.value.imgName = row.imgName
      modifyImgId = row.imgId
    };

    // 改 提交
    const modifySubmitForms = () => {
      modifyRef.value.validate((valid) => {
        if(valid){
          let da = {}
          da.newName = modifyData.value.imgName;
          da.imgId = modifyImgId

          imgs.modify(da).then(res =>{
            console.log(res)
            if(res.code == 200){
              console.log(res)
              ElMessage.success("修改成功")
              getList()
            }else{
              ElMessage.error("error！")
            }
          })
        }else{
          ElMessage.error("error！")
          return false
        }
      })
    }

    const download = (row) => {
      console.log(row.labelId)
      const fileUrl = 'http://localhost:8080/webPage/download/mesh?filename=123141.nii.gz';

// Create a temporary anchor tag
      const a = document.createElement('a');
      a.href = fileUrl;
      a.download = 'myfile.txt';

// Trigger a click on the anchor tag
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
    };

    // 增
    function uploadFiles(event){
      const files = event.target.files;
      const formData = new FormData();

      for(let i=0;i < files.length; i++){
        const file = files[i]
        let id = Date.now() + i
        formData.append("files[]",file, id.toString());
        formData.append("names[]",file.webkitRelativePath);
        if(i == 0){
          formData.append("Ids[]",imgSetId)
          formData.append("Ids[]",userId)
        }
      }
      imgs.make(formData).then(res =>{
        if(res.code == 200){
          console.log(res)
          ElMessage.success("上传成功!")
          getList()
        }else{
          console.log(res)
          ElMessage.error("error！")
        }
      })

    }

    // 选择
    const handleSelectionChange = (selection) => {
      if(imgIds.length !== 0){
        imgIds.splice(0,imgIds.length)
      }
      selection.forEach((item) =>{
        imgIds.push(item.imgsetId)
      })
    }

    // 删
    function removeView(){
      if(imgIds.length === 0){
        ElMessageBox.alert('请勾选想要删除的数据！','Warning',{
          confirmButtonText:"OK"
        })
      }else{
        ElMessageBox.confirm(
            '您确定想要删除选中的数据集吗？',
            'Warning',
            {
              confirmButtonText:'OK',
              cancelButtonText:'Cancel',
              type: 'warning'
            }
        ).then(() => {
          labels.remove(imgIds).then(res => {
            if(res.code == 200){
              ElMessage.success("删除成功")
              getList()
              imgIds.splice(0,imgIds.length)
            }
          })
        }).catch(() => {
          ElMessage({
            type:'info',
            message:"取消删除"
          })
        })
      }
    }

    // 转三D查看
    const toThreeD = (row) => {
      console.log(row.labelId)
      router.push({ name: 'Staging'})
    }

    // 下一页或上一页
    const handleCurrentChange = (newPage) => {
      console.log('Current page:', newPage);
      currentPage.value = newPage;
      const start = (currentPage.value - 1) * pageSize.value
      const end = start + pageSize.value
      displayedData.length = 0
      displayedData.splice(start, end, ...listData.slice(start, end))
    };
    const handleSizeChange = (newSize) => {
      console.log('Current page:', newSize);
      pageSize.value = newSize;

      const start = (currentPage.value - 1) * pageSize.value
      const end = start + pageSize.value
      displayedData.length = 0
      displayedData.splice(start, end, ...listData.slice(start, end))
    }


    return{
      uploadFiles,
      listData,
      selectedKeys,
      handleSelectionChange,
      removeView,
      modifyRef,
      modifyData,
      modifySubmitForms,
      modifyView,
      modifyVisible,
      Delete,
      Search,
      Download,
      currentPage,
      pageSize,
      displayedData,
      handleCurrentChange,
      handleSizeChange,
      Refresh,
      getList,
      setsData,
      toThreeD,
      download
    }
  }
}
</script>

<style scoped>
.drop_box{
  width: 300px;
  height: 200px;
  background-color: white;
  border-radius: 10px;
  border: 2px solid #d9d9d9;
  margin: auto auto auto -30px;
}
.el-table{
  width: 87.7% !important;
  height: 89%;
  margin-left: 15px;
}
.list_data_box{
  width:100%;
  height: 60vh;
  padding:0;
  margin-top: 22px;
}
.content_box{
  width:87.7%;
  height: 20vh;
  padding:0;
  margin-top: 22px;
  background-color: white;
  border-radius: 10px 10px 0 0;
  margin-left: 15px;
}
.gui_box{
  background-color: white;
  border-bottom: 2px solid #d9d9d9;
  width: 87.7%;
  height: 55px;
  margin-left: 15px;
}
.el-input-group{
  width: 30%;
  left: 10px;
}
.imgsets_name{
  font-size: 20px;
  display: flex;
  align-items: center;
}
.imgsets_describe{
  margin: 16px 0;
  font-size: 14px;
  color: #7e7e7e;
  line-height: 24px;
  display: flex;
  padding-left: 24px;
}
.line{
  height: 40px;
  width: 87.7%;
  background-color: white;
  margin-left: 15px;
  border-radius: 10px 10px 0 0;
}
</style>